<!--  -->
<template>
  <div class="system-pdtable-item" v-loading="globalLoading">
    <el-form ref="pdtableForm" :model="pdtable" label-width="180px" v-loading="formLoading">
      <SystemPdtableItemForm ref="systemPdtableItemForm" :pdtable="pdtable" :changePdtable="changePdtable"
         :globalLoading="globalLoading" :resetImageList="resetImageList" :system="system" :categories="categories" :contentChange="contentChange" :categoryTreeShow="categoryTreeShow" :isSetUecontent="isSetUecontent"/>
      <el-form-item class="footfixed">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList">保存并返回系统列表</el-button>
        <el-button @click="goSystemList">返回系统列表</el-button>
      </el-form-item>
    </el-form>
    <!-- 分类级别树形结构显示 -->
    <TreeDialog :data="categoryTreeDialog" ref="categoryTreeDialog" title="分类级别树形结构显示" />
  </div>
</template>

<script>
import SystemPdtableItemForm from '@/components/main/user/system/pdtable/item/SystemPdtableItemForm.vue'
import TreeDialog from '@/components/common/dialog/TreeDialog.vue'
import * as functions from '@/core/functions.js'
export default {
  created () {
    let query = this.$route.query
    if (!query || !query.sid || !query.id) {
      this.$message.error('未能获取到正确的数据')
      return
    }
    let systemId = query.sid
    let id = query.id
    // 获取系统信息
    this.$post('/system/info', { id: systemId }).then((resoponse) => {
      if (resoponse && resoponse.id) {
        this.system = resoponse
        this.pdtable.seo.systemId = this.pdtable.systemId = this.system.id
        if (this.system.systemType && this.system.systemType.id === 8) {
          // 获取所有的分类信息
          this.$post('/category/table-data-infos-by-system-id', { systemId: systemId }).then((resoponse) => {
            if (resoponse.categories) {
              this.categories = resoponse.categories
            } else {
              this.categories = {}
            }
            if (resoponse.categoryIds && resoponse.categoryIds.length > 0) {
              this.pdtable.categoryIds = resoponse.categoryIds
            }
            this.initComplete.categories = true
          })
        } else if (this.system.systemType && this.system.systemType.id === 4) {
          // 获取短标题信息
          this.initComplete.categories = true
        } else {
          // 不需要获取分类、短标题信息
          this.initComplete.categories = true
        }
        // 获取内容信息
        if (id > 0) {
          this.isSetUecontent = false
          // 修改
          this.$post('/system/pdtable/data-info', {id: id}).then(response => {
            if (response) {
              this.pdtable = initPdtable(response, this)
            } else {
              console.error(response)
            }
            this.initComplete.titleItem = true
            this.initComplete.data = true
            this.initComplete.attr = true
            this.isSetUecontent = true
          })
        } else {
          this.isSetUecontent = false
          // 获取信息系统属性
          this.$post('/system/pdtable/title-infos', { systemId: systemId }).then(response => {
            let titleItem = initAttrByPdtableAttr(response)
            this.pdtable.titleItem = titleItem
            this.initComplete.titleItem = true
            this.isSetUecontent = true
          })
          this.$post('/url/item-custom-link-path-one-group-by-system-id', {systemId: systemId}).then(response => {
            if (response && response.length > 0) {
              this.pdtable.customLink.pathOneGroup = response
            }
          })
          // 新增
          this.initComplete.data = true
        }
      }
      this.initComplete.system = true
    })
  },
  data () {
    return {
      // 全局加载
      globalLoading: true,
      // 表单加载
      formLoading: false,
      // 判断是否加载完成的四个加载项目
      initComplete: {
        system: false,
        data: false,
        titleItem: false,
        categories: false
      },
      // 获取系统的分类信息
      categories: {},
      // 当前的系统
      system: {},
      // 表单数据
      pdtable: {
        // 基础信息
        id: 0,
        systemId: 0,
        // 状态 （0）-不显示 （1）-显示
        status: 1,
        // 属性信息
        titleItem: [],
        // 文件信息
        file: {},
        fileRepertoryConfig: '',
        fileRepertoryId: null,
        // 图片信息
        imageList: [],
        imageRepertoryId: null,
        imageRepertoryConfig: {},
        // 分类信息
        categoryIds: [],
        // 富文本
        content: '',
        // 发布时间
        releasedAt: new Date(),
        // seo 信息
        seo: { id: 0, systemId: 0, title: '', keywords: '', description: '' },
        // 自定义链接信息
        customLink: { id: 0, systemId: 0, status: 0, path: [], lanno: '', pathOneGroup: [], suffix: '.html' }
      },
      isSetUecontent: false
    }
  },
  computed: {
    categoryTreeDialog () {
      let result = getCategoryTreeData(this.categories, 0)
      return result
    }
  },
  watch: {
    initComplete: {
      handler (newVal) {
        this.$nextTick(() => {
          if (newVal.system && newVal.data && newVal.titleItem) {
            // 初始化请求完毕
            this.globalLoading = false
          }
        })
      },
      deep: true
    }
  },
  methods: {
    // 保存
    onSubmit (callback) {
      let bool = true
      let titlename
      let titleItem = []
      this.pdtable.titleItem.forEach(el => {
        let obj = {
          pdtableTitleId: el.pdtableTitleId,
          value: el.value
        }
        titleItem.push(obj)
        if (el.type === 5 && el.value.trim() === '') {
          titlename = el.title
          bool = false
        }
      })
      if (!bool) {
        this.$message.error(`${titlename}字段不能为空！`)
        return
      }
      let itemCustomLinkInfo = this.getCustomLink()
      let itemCustomLink
      if (!itemCustomLinkInfo.bool) {
        return
      } else {
        itemCustomLink = {
          path: itemCustomLinkInfo.path,
          status: itemCustomLinkInfo.status
        }
      }
      let param = {
        fileRepertoryConfig: this.pdtable.fileRepertoryConfig,
        fileRepertoryId: this.pdtable.fileRepertoryId,
        id: this.pdtable.id,
        imageRepertoryConfig: this.pdtable.imageRepertoryConfig,
        imageRepertoryId: this.pdtable.imageRepertoryId,
        status: this.pdtable.status,
        systemId: this.pdtable.systemId,
        titleItem: titleItem,
        seo: JSON.parse(JSON.stringify(this.pdtable.seo)),
        releasedAt: this.pdtable.releasedAt,
        content: this.$refs['systemPdtableItemForm'].getContent(),
        itemCustomLink: itemCustomLink,
        categoryIds: JSON.parse(JSON.stringify(this.pdtable.categoryIds))
      }
      this.formLoading = true
      this.$jpost('/system/pdtable/data-save', param).then(response => {
        if (response) {
          if (typeof callback === 'function') {
            callback()
          }
          this.pdtable = initPdtable(response, this)
        } else {
          console.error(response)
        }
        this.formLoading = false
      })
    },
    // 保存并返回系统列表
    onSubmitAndGoSystemList () {
      this.onSubmit(() => {
        this.goSystemList()
      })
    },
    // 返回系统列表
    goSystemList () {
      let fullPath = functions.getSystemListPathByItem(this.system)
      if (!fullPath) {
        return
      }

      // 存储系统页面页码，如果从编辑页返回列表页fromItem改为true
      let systbPageCur = JSON.parse(sessionStorage.getItem('systbPageCur' + this.system.id))
      if (systbPageCur) {
        systbPageCur.fromItem = true
        sessionStorage.setItem('systbPageCur' + this.system.id, JSON.stringify(systbPageCur))
      }

      this.$store.dispatch('navAppendAndClose', { path: fullPath, close: this.$route.fullPath })
    },
    // 改变pdtable数据
    changePdtable (infos) {
      this.pdtable = infos
    },
    // 当内容变化的时候
    contentChange (content) {
      this.pdtable.content = content
    },
    // 点击显示分类树形结构弹窗
    categoryTreeShow () {
      this.$refs['categoryTreeDialog'].show()
    },
    // 重置当前的图片列表
    resetImageList (list) {
      this.pdtable.imageList = list
      if (this.pdtable.imageList.length < 1) {
        this.pdtable.imageRepertoryConfig = {}
        this.pdtable.imageRepertoryId = null
      }
    },
    // 获取产品自定义链接数据
    getCustomLink () {
      return this.$refs['systemPdtableItemForm'].getCustomLink()
    }
  },
  components: {
    TreeDialog,
    SystemPdtableItemForm
  }
}

// 初始化 pdtable 数据使其符合 this.pdtable 中的数据格式
function initPdtable (data, vm) {
  let file = data.one && data.one.file && data.one.file.hrepertory && data.one.file.srepertoryQuote ? {
    id: data.one.file.hrepertory.id,
    originalFilename: data.one.file.hrepertory.originalFilename,
    suffix: data.one.file.hrepertory.suffix
  } : {}
  let fileRepertoryId = data.one && data.one.file && data.one.file.hrepertory ? data.one.file.hrepertory.id : null

  let imageList = []
  let imageRepertoryId = null
  let imageRepertoryConfig = {}
  if (data.one && data.one.image && data.one.image.hrepertory && data.one.image.srepertoryQuote) {
    let item = data.one.image.hrepertory
    let quote = data.one.image.srepertoryQuote
    let config
    if (quote.config) {
      config = JSON.parse(quote.config)
    }
    let title = config && config.title ? config.title : item.originalFilename
    let alt = config && config.alt ? config.alt : item.originalFilename

    let repertoryImageSrc = { hostId: vm.$store.state.host.id, repertoryId: item.id, suffix: item.suffix, type: item.type, link: item.link }
    imageList.push({
      id: item.id,
      src: functions.getRepertoryImageSrc(repertoryImageSrc),
      title: title,
      alt: alt
    })
    imageRepertoryId = item.id
    imageRepertoryConfig = {
      title: title,
      alt: alt
    }
  }

  let titleItem = []
  if (data.one && data.one.listItem && data.one.listItem.length > 0 && data.title && data.title.length > 0) {
    data.title.forEach(el => {
      if (el.type === 1 || el.type === 5) {
        let ite = {
          pdtableTitleId: el.id,
          title: el.title,
          value: '',
          type: el.type
        }
        data.one.listItem.forEach(ele => {
          if (el.id === ele.pdtableTitleId) {
            ite.value = ele.value
          }
        })
        titleItem.push(ite)
      }
    })
  }

  let listCategoryQuote = data.one.listCategoryQuote
  let categoryIds = []
  if (listCategoryQuote && listCategoryQuote.length > 0) {
    categoryIds = listCategoryQuote.map(element => {
      return element.scategoriesQuote.categoryId
    })
  }

  let sseoItem = data.one.sseoItem
  let seo = { id: 0, systemId: data.system.id, title: '', keywords: '', description: '' }
  if (sseoItem && sseoItem.id) {
    seo = {
      id: sseoItem.id,
      systemId: sseoItem.systemId,
      title: sseoItem.title,
      keywords: sseoItem.keywords,
      description: sseoItem.description
    }
  }

  let customLink = { id: 0, systemId: 0, status: 0, path: [], lanno: '', pathOneGroup: [], suffix: '.html' }
  if (data.one.customLink) {
    customLink = data.one.customLink
  }

  return {
    id: data.one.data.id,
    systemId: data.system.id,
    releasedAt: data.one.data.releasedAt,
    status: data.one.data.status,
    titleItem: titleItem,
    content: data.one.data.content,
    // 文件
    file: file,
    fileRepertoryConfig: '',
    fileRepertoryId: fileRepertoryId,
    // 图片
    imageList: imageList,
    imageRepertoryId: imageRepertoryId,
    imageRepertoryConfig: imageRepertoryConfig,
    // 分类信息
    categoryIds: categoryIds,
    // seo 信息
    seo: seo,
    // 自定义链接
    customLink: customLink
  }
}

function initAttrByPdtableAttr (data) {
  let result = []
  if (!data || data.length < 1) {
    return []
  }
  data.forEach((element) => {
    if (element.type === 1 || element.type === 5) {
      result.push({
        pdtableTitleId: element.id,
        title: element.title,
        value: '',
        type: element.type
      })
    }
  })
  return result
}
function getCategoryTreeData (data, key) {
  if (data.length < 1) {
    return []
  }
  let result = []
  for (let i in data[key]) {
    let item = data[key][i]
    let children
    if (data.hasOwnProperty(item.id)) {
      children = getCategoryTreeData(data, item.id)
    }
    let element = {}
    element.label = item.name
    if (children) {
      element.children = children
    }
    result.push(element)
  }
  return result
}
</script>
<style scoped lang="scss">
.system-pdtable-item {
  padding-bottom: 60px;
  .header {
    min-height: 36px;
    .border {
      width: 100%;
      height: 1px;
      border-bottom: 2px solid #e5e5e5;
      margin-top: 12px;
      margin-bottom: 24px;
    }
  }
}
.footfixed {
  position: fixed;
  z-index: 1000;
  bottom: 0;
  left: 220px;
  right: 0;
  background: #fff;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  margin-bottom: 0 !important;
  text-align: right;
}
</style>
